import { saveAs } from 'file-saver'

export const htmlHeader = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Title</title>
    </head>
    <body>
      htmlCode
    </body>
    </html>
`

export const htmlInsertHeader = (htmlCode: string) => {
  return htmlHeader.replace('htmlCode', htmlCode)
}

/**
 * 生成代码
 */

export function domToString(id: string) {
  const node: any = document.getElementById(id)
  return node?.outerHTML?.replace(/&quot;/g, "'")
}

export const generateCode = (domId: string, variableList: any[] = []) => {
  // 获取该元素的HTML字符串
  const strHtml = domToString(domId)
  // 移除注释部分,并移除多余的属性

  let tempCode = strHtml
    .replace(/<!--[\s\S]*?-->/g, '')
    .replace(/id="[^"]*"/g, '')
    .replace(/(\s+data-v-[^='"\s]+=['"]?[^'"]*['"]?)/gi, '')
  console.log(variableList?.length, 'variableList?.length')
  if (variableList?.length) {
    variableList.forEach((item: any) => {
      tempCode = tempCode.replaceAll(`${item.value}`, item.preview)
    })
  }
  return tempCode
}

/**
 * 复制内容
 */
export const setClipboardData = (data: any) => {
  return new Promise((success) => {
    const textarea: any = document.createElement('textarea')
    textarea.value = data
    textarea.readOnly = 'readOnly'
    document.body.appendChild(textarea)
    textarea.select()
    textarea.setSelectionRange(0, data.length)
    document.execCommand('copy')
    textarea.remove()
    success(data)
  })
}

/**
 * 将字符串保存为文件
 */

export const saveAsFile = (codeStr: string, fileName: string) => {
  const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' })
  saveAs(blob, fileName)
}
